SELECT distinct ubi.con_anno,ubi.con_id,ubi.att_idext POD,ubi.att_id ATTID,
       misval.smis_mat MATSM,
       TRUNC (let.ver_dtfine) data_ultima_lettura,
       misval.fuco_id  "Funzione consumo",
       misval.faco_id FASCIA ,
       misval.lmis_val ultima_lettura,
       misval.lmis_valcon consumo
               
     
       FROM v_conubifrn ubi, lettura let, v_letmisval misval,v_attgmis mi,STRMIS ST,
   --*********************************************    
       (SELECT distinct let.att_id, 
       
      max(TRUNC (let.ver_dtfine)) data_lettura
      
       FROM v_lettura let, v_letmisval misval
    WHERE 
       misval.let_id = let.let_id
      and let.az_id = '01'
      and misval.az_id = let.az_id
      AND let.let_id = misval.let_id
     ------------------------****------------------------------------
      
      
      
      ------------------------****------------------------------------
      group by let.att_id) xx
     --***************************************************
       
    WHERE --ubi.ser_id = 03
       ubi.cuf_id = let.cuf_id
     --AND let.let_flpro = 0  ---- 0 autolettura 1 - lettura normale
      AND let.let_id = misval.let_id
      AND MISVAL.SMIS_MAT=ST.SMIS_MAT
      and ST.ver_dtfine = to_date ('31129999','ddmmyyyy')
      and xx.att_id = ubi.att_id
      and xx.data_lettura = TRUNC (let.ver_dtfine)
      --and misval.smis_mat = xx.smis_mat
      --and  ubi.tcon_id = 20   --domesico
      --and mi.tsrc_id in('11','16')   --attiva monorario -- attiva multiorario --
      --and   (ubi.tcon_id = 20 or (ubi.tcon_id = 21 and   mi.tgm_id in (13)))   -- DOMESTICO   , ALTRI USI non orario
      and mi.att_id =UBi.att_id
      and mi.AZ_ID = ubi.az_id
      AND ST.AZ_ID =ubi.az_id
      and let.az_id = ubi.az_id
      and ubi.az_id = ubi.az_id
      and misval.az_id = let.az_id
      
      --and misval.smis_mat <> 'ND'
      --and ubi.att_idext like 'IT%'
      and mi.STA_IDSYS=2
      and mi.ver_dtfine = to_date ('31129999','ddmmyyyy')
      and xx.data_lettura BETWEEN mi.ver_dtini AND mi.ver_dtfine
      and ubi.ver_dtfine = to_date ('31129999','ddmmyyyy')
      and ubi.STA_IDSYS=2
      
      
      order by ubi.con_anno,ubi.con_id,misval.smis_mat,misval.fuco_id,
       misval.faco_id 

      
     
     
     
 
      
      
 






    
      
      


      
      



